package com.suanfa.sort.ti;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @author jukg
 * @date 2025/01/06 18:07
 * @description
 */
public class RandomizedSet {

    HashMap<Integer, Integer> hashMap;
    List<Integer> values;
    Random random ;

    public RandomizedSet() {
        hashMap = new HashMap();
        values =  new ArrayList<Integer>();
        random = new Random();
    }

    public boolean insert(int val) {
        if(hashMap.containsKey(val)){
            return false;
        }
        values.add(val);
        hashMap.put(val, values.size()-1);
        return true;
    }

    public boolean remove(int val) {
        if(!hashMap.containsKey(val)){
            return false;
        }
        Integer index = hashMap.get(val);
        values.remove(index);
        hashMap.remove(val);
        return true;
    }

    public int getRandom() {
        if(values.size()>0){
            int index = random.nextInt(values.size()-1);
            return values.get(index);
        }
       return 0;
    }

    public static void main(String[] args) {
        RandomizedSet set = new RandomizedSet();
        System.out.println(set.insert(1));
        System.out.println(set.remove(2));
        System.out.println(set.insert(2));
        System.out.println(set.getRandom());
        System.out.println(set.remove(1));
        System.out.println(set.insert(2));
        System.out.println(set.getRandom());
    }
}
